﻿#include "ssMsgThread.h"
#include "../tools/ssTools.h"
#include "../time/ssTimer.h"
//#include <cstdio>

namespace StarSeeker
{

ssMsgThread::ssMsgThread()
{
	m_maxMsgCount = 1000000;
	m_msgOffset = 0;
	//m_condPut.BindLock(&m_mutex);
	m_condGet.BindLock(&m_mutex);
}

ssMsgThread::~ssMsgThread()
{
	ExitThread();
	//printf("CAO\n");
}

bool ssMsgThread::PostMsg(ssMsg_s &m)
{
	//if (m_msgList.Size() > m_maxMsgCount)
	//{
	//	return false;
	//}
	SS_MUTEX_LOCK(m_mutex) //锁定互斥量
	//while (m_msgList.Size() >= m_maxMsgCount)
	//{
	//	//printf("put wait\n");
	//	m_condPut.Wait(); //条件变量等待
	//}
	m_msgList[m_msgOffset].PushBack(m);
	//printf("put\n");
	m_condGet.NotifyAll(); //通知可以读取数据
	SS_MUTEX_UNLOCK(m_mutex)

	return true;
}

bool ssMsgThread::PostMsg(u32 msgID, u32 subID, ulint param1, ulint param2, ulint param3)
{
	ssMsg_s msg(msgID, subID, param1, param2, param3);
	return PostMsg(msg);
}

void ssMsgThread::ThreadMemberFunc()
{
	OnThreadRun();
	while (!IsRequestStop())
	{
		ssList<ssMsg_s>* tempList = 0;
		SS_MUTEX_LOCK(m_mutex); //锁定互斥量
		while (m_msgList[m_msgOffset].Size()==0)
		{
			//printf("get wait\n");
			m_condGet.Wait(); //条件变量等待
		}
		tempList = m_msgList + m_msgOffset;
		m_msgOffset = (m_msgOffset + 1) % 2;
		SS_MUTEX_UNLOCK(m_mutex);
		//m_condPut.NotifyAll(); //通知可以写入数据

		ssList<ssMsg_s>::Iterator itr = tempList->Begin();
		while(itr.IsVaild())
		{
			switch (itr.Data()->msgID)
			{
			case SS_THREAD_STOP:
				RequestStop();
				break;
			case SS_THREAD_CLEAR:
				SS_MUTEX_LOCK(m_mutex)
					m_msgList[0].Release();
					m_msgList[1].Release();
				SS_MUTEX_UNLOCK(m_mutex)
				break;
			default:
				HandleMessage(*itr.Data());
				break;
			}
			++itr;
		}
		//printf("get%d\n", m_tempList.Size());
		tempList->Empty();
	}
	OnThreadExit();
}

void ssMsgThread::ExitThread()
{
	if (!IsRequestStop())
	{
		ssMsg_s m;
		m.msgID = SS_THREAD_STOP;
		PostMsg(m);
		ssThreadBase::Sleep(100);
		WaitForExit();
	}
}

void ssMsgThread::SetMaxMsgCount(u32 ct)
{
	m_maxMsgCount = ct;
}

Byte8_u ssMsgThread::GetMsgCount()
{
	Byte8_u ret;
	ret.u32p[0] = (u32)m_msgList[0].Size();
	ret.u32p[1] = (u32)m_msgList[1].Size();
	return ret;
}

Byte8_u ssMsgThread::GetMsgMaxCount()
{
	Byte8_u ret;
	ret.u32p[0] = (u32)m_msgList[0].Total();
	ret.u32p[1] = (u32)m_msgList[1].Total();
	return ret;
}

}
